Skip to main content
Version: 1.0.0

updateVariantHelper

Function Name: updateExistingVariantDocument

Author: Domenico Cerone Creation Date: 09/10/2025
Last Reviewer: Domenico Cerone

Trigger: Helper function (called by updateVariantProduct)

Purpose: Updates an existing document in the 'Variants' Firestore collection using updated mapped JSON data. This function handles complete field refresh and tag regeneration while maintaining workflow fields unchanged.

Detailed Functionalityโ€‹

This helper function performs comprehensive updates to existing Variants documents with complete tag regeneration using thread-safe utilities.

1. EXISTING DOCUMENT LOADINGโ€‹

  • Receives variantRef as document ID parameter
  • Loads existing document from 'Variants' collection
  • If NOT EXISTS โ†’ error (does not create new documents)
  • If EXISTS โ†’ proceeds with update (STEP 2)

2. FIELD UPDATES AND TAG REGENERATIONโ€‹

  • Updates only fields that come from mapped JSON
  • COMPLETELY REGENERATES TAGS (like populateVariantFromSku):
    • list_size_color_tags with frameColor and size tag IDs
    • Searches/creates tags in Tags collection using tagUtils
    • Thread-safe to avoid duplicates
  • Maintains all existing workflow fields unchanged
  • Updates lastUpdate with current timestamp

Fields Updated from Mapped JSONโ€‹

Base Variant Fields:

  • eanCode โ† eanCode
  • frameColor โ† frameColor
  • lensesColor โ† lensesColor
  • glassesName โ† glassesName
  • mainBrandRef โ† brand ID (searches/creates in MainBrands collection)
  • upcCode โ† upcCode
  • poster โ† poster
  • poster2 โ† poster2
  • poster3 โ† poster3
  • poster4 โ† poster4

Boolean Fields:

  • isADV โ† isADV (converted from "YES"/"NO" to boolean)

Timestamp Fields:

  • lastUpdate โ† current timestamp
  • skuReleaseDate โ† skuReleaseDate (if present)
  • skuEndDate โ† skuEndDate (if present)
  • advStartDate โ† advStartDate (if present)
  • advEndDate โ† advEndDate (if present)

Size Object (all fields as strings):

  • size.bridge โ† bridge
  • size.frameWidth โ† frameWidth
  • size.lensHeight โ† lensHeight
  • size.lensWidth โ† lensWidth
  • size.size โ† size
  • size.templeLength โ† templeLength
  • size.frontHeight โ† frontHeight
  • size.hingeToHinge โ† hingeToHinge
  • size.lensCircumference โ† lensCircumference
  • size.lensAngle โ† lensAngle
  • size.phantoscopicAngle โ† phantoscopicAngle

Special Arrays (regenerated from mapped JSON):

  • list_size_color_tags โ† [frameColor tag ID, size tag ID] (searches/creates in Tags collection)
  • list_images โ† list_images (array of objects with view and url)

Fields Maintained Unchangedโ€‹

All workflow and configuration fields remain unchanged:

  • skuModel (primary identifier)
  • assignedTo, assignmentDate, dataTaken
  • batch, productRef, catalogOrdersRef, prioritiesModeling
  • loadingId, mainModel, modelPriority, modelViewerUrl
  • modify_model (complete object)
  • posterNoBackground, primaryFrameColorHex, primaryLensesColorHex
  • priority, refLogVariant, secondaryFrameColorHex, secondaryLensesColorHex
  • status, templeColor
  • urlDE, urlES, urlFR, urlGlobal, urlGlobalComplete, etc.
  • variantCode, list_notes

Tag Creation Functionsโ€‹

The function uses specialized thread-safe tag creation functions:

Frame Color and Size Tags:

  • findOrCreateTag() - Creates/finds tags with specified type and group
    • Frame Color: type="frameColor", group="Frame Color", groupOrder=11
    • Size: type="size", group="Size", groupOrder=10

Brand Management:

  • findOrCreateMainBrand() - Creates/finds brands in MainBrands collection

Input Parametersโ€‹

Function Signature:

async function updateExistingVariantDocument(variantRef, mappedJsonData, requestId)

Parameters:

  • variantRef (string, required): ID of the Variants document to update
  • mappedJsonData (Object, required): Updated mapped JSON data
  • requestId (string, required): Request ID for logging

Expected mappedJsonData Structure:

This data comes from the main function after processing the CatalogOrder document and downloading/mapping fresh data from Safilo APIs:

{
"mapped_data": {
"eanCode": "0762753916013",
"frameColor": "BLACK",
"lensesColor": "GREY GRADIENT",
"glassesName": "BOSS 1234/S",
"mainBrandRef": "BOSS EYEWEAR",
"upcCode": "762753916013",
"poster": "https://firebasestorage.googleapis.com/v0/b/.../view_00.jpg",
"poster2": "https://firebasestorage.googleapis.com/v0/b/.../view_07.jpg",
"poster3": "https://firebasestorage.googleapis.com/v0/b/.../view_02.jpg",
"poster4": "https://firebasestorage.googleapis.com/v0/b/.../view_01.jpg",
"isADV": "YES",
"bridge": "18",
"frameWidth": "140",
"lensHeight": "45",
"lensWidth": "54",
"size": "54",
"templeLength": "145",
"frontHeight": "45",
"hingeToHinge": "140",
"lensCircumference": "160",
"lensAngle": "6",
"phantoscopicAngle": "12",
"list_images": [
{
"view": "00",
"url": "https://firebasestorage.googleapis.com/v0/b/.../view_00.jpg"
},
{
"view": "01",
"url": "https://firebasestorage.googleapis.com/v0/b/.../view_01.jpg"
}
],
"skuReleaseDate": 1640995200000,
"skuEndDate": 1672531200000,
"advStartDate": 1640995200000,
"advEndDate": 1672531200000
}
}

Output (Success)โ€‹

{
"success": true,
"operation": "update",
"documentId": "existing_variant_id",
"skuModel": "20637008650QT",
"message": "Documento Variants aggiornato per ID existing_variant_id",
"updatedFields": [
"eanCode",
"frameColor",
"lensesColor",
"glassesName",
"mainBrandRef",
"upcCode",
"poster",
"poster2",
"poster3",
"poster4",
"isADV",
"lastUpdate",
"list_size_color_tags",
"list_images",
"size",
"skuReleaseDate",
"skuEndDate",
"advStartDate",
"advEndDate"
]
}

Output (Error)โ€‹

{
"success": false,
"operation": "error",
"documentId": "existing_variant_id",
"skuModel": "UNKNOWN",
"message": "Errore nell'aggiornamento documento Variants: Document not found",
"error": "Document not found"
}

Size Object Structureโ€‹

The function creates a complete size object with all measurements as strings:

{
"size": {
"bridge": "18",
"frameWidth": "140",
"lensHeight": "45",
"lensWidth": "54",
"size": "54",
"templeLength": "145",
"frontHeight": "45",
"hingeToHinge": "140",
"lensCircumference": "160",
"lensAngle": "6",
"phantoscopicAngle": "12"
}
}

Tag Array Structureโ€‹

The function regenerates the list_size_color_tags array with tag IDs:

{
"list_size_color_tags": ["frameColorTagId123", "sizeTagId456"]
}

Tag Creation Process:

  1. Frame Color Tag: Searches/creates tag with name=frameColor, type="frameColor", group="Frame Color"
  2. Size Tag: Searches/creates tag with name=size, type="size", group="Size"
  3. Thread-Safe: Uses mutex synchronization to prevent duplicate tag creation

Date Handlingโ€‹

The function handles timestamp fields with automatic conversion:

  • Input: Unix timestamp (number) or current timestamp
  • Output: JavaScript Date object
  • Validation: Checks if timestamp is valid before conversion
  • Fallback: Uses current timestamp if invalid data provided
  • Main Function: updateVariantProduct - Main function that calls this helper
  • Product Helper: updateProductHelper - Parallel helper for Products collection
  • Tag Utilities: tagUtils - Thread-safe tag creation utilities with mutex synchronization to prevent duplicates

Error Handlingโ€‹

The function includes comprehensive error handling:

  • Document Not Found: Returns error if variantRef doesn't exist
  • Invalid Data: Validates mappedJsonData structure
  • Tag Creation Errors: Continues operation even if some tags fail
  • Firestore Errors: Catches and logs database operation errors
  • Brand Creation Errors: Falls back to empty string if brand operations fail
  • Date Conversion Errors: Uses current timestamp as fallback

Performance Considerationsโ€‹

  • Thread-Safe Operations: All tag operations use mutex synchronization
  • Parallel Tag Creation: Frame color and size tags created simultaneously
  • Minimal Database Writes: Only updates changed fields
  • Error Isolation: Individual tag failures don't block document update
  • Efficient Queries: Uses document ID for direct access